package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.client.ArticleFeign;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.article.dtos.AuthorDto;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.dtos.UserAuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserAuth;
import com.heima.user.mapper.ApUserAuthMapper;
import com.heima.user.service.ApUserAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.ApUserService;
import com.heima.wemedia.client.WemediaFeign;
import com.sun.xml.bind.v2.model.core.ID;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 * @author LX
 * @since 2022-06-18
 */
@Slf4j
@Service
public class ApUserAuthServiceImpl extends ServiceImpl<ApUserAuthMapper, ApUserAuth> implements ApUserAuthService {

    @Autowired
    private ApUserService apUserService;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private WemediaFeign wemediaFeign;

    @Override
    public PageResult<UserAuthDto> findByPage(AuthDto dto) {
//        设置分页条件
        Page<ApUserAuth> ipage = new Page<>(dto.getPage(),dto.getSize());
//        设置查询条件
        LambdaQueryWrapper<ApUserAuth> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dto.getStatus() != null,ApUserAuth::getStatus,dto.getStatus());
//        分页查询
        IPage<ApUserAuth> authIPage = page(ipage, queryWrapper);

        if(authIPage == null || CollectionUtils.isEmpty(authIPage.getRecords())){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        对象属性拷贝
        List<UserAuthDto> userAuthDtoList = BeanHelper.copyWithCollection(authIPage.getRecords(), UserAuthDto.class);
//        构造返回对象
        return new PageResult(dto.getPage(),dto.getSize(),authIPage.getTotal(),userAuthDtoList);
    }

    @Override
    //@Transactional(rollbackFor = Exception.class)  //本地事务
    @GlobalTransactional(rollbackFor = Exception.class) //分布式事务
    public void authUser(AuthDto dto, int status) {

        ApUserAuth apUserAuth = new ApUserAuth();
        apUserAuth.setId(dto.getId());
        apUserAuth.setStatus(status);
        if (status == 2) {
            apUserAuth.setReason(dto.getMsg());
        }
        //修改用户审核状态
        boolean b = updateById(apUserAuth);
        if (!b) {
            log.error("修改认证状态失败,auth_id={}", dto.getId());
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        //如果审核不通过,直接结束
        if (status == 2) {
            log.info("用户审核不通过直接结束,auth_id={}", dto.getId());
            return;
        }
        apUserAuth = getById(dto.getId());
        Integer apUserId = apUserAuth.getUserId();
        //根据apuserid 查询apuser对象,获取参数
        ApUser apUser = apUserService.getById(apUserId);
        //创建自媒体用户,远程调用自媒体服务
        WmUserDto wmUserDto = new WmUserDto();

        wmUserDto.setApUserId(apUserId);
        wmUserDto.setName(apUser.getName());
        wmUserDto.setPassword(apUser.getPassword());
        wmUserDto.setPhone(apUser.getPhone());
        wmUserDto.setStatus(9);
        try {
            Integer wmUserId = wemediaFeign.saveWmUser(wmUserDto);
            wmUserDto.setId(wmUserId);
        } catch (Exception e) {
            log.error("远程创建调用自媒体,创建自媒体用户失败");
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        //远程调用文章服务 创建文章作者
        AuthorDto authorDto = new AuthorDto();

        authorDto.setName(apUser.getName());
        authorDto.setUserId(apUserId);
        authorDto.setType(2);
        authorDto.setWmUserId(wmUserDto.getId());
        try {
            Integer authorId = articleFeign.saveAuthor(authorDto);
        } catch (Exception e) {
            log.error("远程创建调用作者服务,创建作者用户失败");
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        //修改普通用户flag改成1
        apUser = new ApUser();
        apUser.setId(apUserId);
        apUser.setFlag(1);
        boolean b1 = apUserService.updateById(apUser);
        if (!b1) {
            log.error("修改apUser的flag失败,apUserId={}", apUserId);
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }


        //System.out.println(1/0);
    }

}
